/**/
Date.prototype.pattern=function(fmt) {           
    var o = {           
    "M+" : this.getMonth()+1, // 月份
    "d+" : this.getDate(), // 日
    "h+" : this.getHours(), // 小时
    "H+" : this.getHours(), // 小时
    "m+" : this.getMinutes(), // 分
    "s+" : this.getSeconds(), // 秒
    "q+" : Math.floor((this.getMonth()+3)/3), // 季度
    "S" : this.getMilliseconds() // 毫秒
    },
    week = {           
    "0" : "/u65e5",           
    "1" : "/u4e00",           
    "2" : "/u4e8c",           
    "3" : "/u4e09",           
    "4" : "/u56db",           
    "5" : "/u4e94",           
    "6" : "/u516d"          
    },k;           
    if(/(y+)/.test(fmt)){           
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));           
    }           
    if(/(E+)/.test(fmt)){           
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);           
    }           
    for(k in o){           
        if(new RegExp("("+ k +")").test(fmt)){           
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));           
        }           
    }           
    return fmt;           
};

angular.module('uscheduleFilters', [])
	.filter('dateFilter',['$filter',function($filter){
		return function(time){
			if (time <= 0) {
				return "--/--";
			} else {
				return $filter("date")(time,"yyyy-MM-dd HH:mm:ss");
			}
		}
	}]);

var transFn = function(data) {
		return $.param(data);
	},
	postCfg = {
		headers : {
			'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		transformRequest : transFn
	},
	mainApp = angular.module('mainApp', [ 'ngRoute','ngAnimate', 'ui.bootstrap','uscheduleFilters' ]);

mainApp.directive('pager', function() {
    return {
        restrict: 'EA',
        templateUrl: 'pages/common/pager.jsp',
        replace: true,
        transclude : true,
        scope:{
        	pageritem:"=pagerItem"
        }
    };
});

mainApp.service( 'smartPager', [ '$rootScope', function( $rootScope ) {
	
	function showMessageTop(content,time){
		// igone
	}
	
	function pager(_scope, opts){
		this.id = "pager" + new Date().getTime();
		this.ckname = this.id + "ck";
		this.checkAll = false;
		this._scope = _scope;
		this.curPage = 1;
		this.totalPage = 1;
		this.rowCount = 0;
		this.options = $.extend({pageSize:20, singleSelect: false, url:'', param : {}}, opts);
		this.idKey = this.options.idKey;
		this.singleSelect = this.options.singleSelect;
		this.pageSize = this.options.pageSize;
		this.items = [];
		this.hasNextPage = false;
		this.hasPerPage = false;
		
	};
	
	pager.prototype.query = function (_opts) {
		var _this = this;
		if (_opts) {
			$.ajax({
				type: "POST",
				async: true,
				url: _opts.url, 
				dataType: "json",
				data: _opts.params,
				beforeSend:function() {
					// showMessageTop($.i18n.prop("common_loading_msg"));
					if (_this.options.beforeSend) {_this.options.beforeSend();}
				}, 
				success: function(data){
					_this.parse(data, _opts);
			    },
			    error : function (err){
					if (_this.options.error) {_this.options.error(err);}
			    },
			    complete:function(){
					// showMessageTop($.i18n.prop("common_load_complate"),3000);
			    }
			});
		}
	};
	
	pager.prototype.parse = function (data, _opts) {
		var _this = this;
		_this._scope.$apply(function () {
			_this.checkAll = false;
			_this.items = data.data;
			_this.curPage = data.page || 1;
			_this.rowCount = data.total || 0;
			_this.pageSize = _this.pageSize==0?65535:_this.pageSize;
			_this.totalPage = parseInt(_this.rowCount / _this.pageSize);
			if ((_this.rowCount % _this.pageSize) > 0) {
				_this.totalPage = _this.totalPage + 1;
			}
			_this.hasPerPage = _this.curPage > 1;
			_this.hasNextPage = _this.curPage < _this.totalPage;
			if (_this.options.success) {_this.options.success(data);}
		});
	};
	
	pager.prototype.setPageSize = function (_pageSize) {
		this.pageSize = _pageSize;
	} ;
	
	pager.prototype.load = function (_param) {
		if (_param) {
			angular.extend(this.options.params,_param);
		}
		if (this.options && this.options.url) {
			this.options.params.page = 1;
			this.options.params.rows = this.pageSize;
			this.query({
				url:this.options.url,
				params:this.options.params
			});
		}
	};
	
	pager.prototype.reload = function () {
		if (this.options && this.options.url) {
			this.options.params.page = this.curPage;
			this.options.params.rows = this.pageSize;
			this.query({
				url:this.options.url,
				params:this.options.params
			});
		}
	};
	
	pager.prototype.toPrevPage = function() {
		if (this.hasPerPage) {
			if (this.options && this.options.url) {
				if (this.curPage > this.totalPage || this.curPage <= 1) {
					this.curPage = 1;
				} else {
					this.curPage = this.curPage - 1;
				}
				this.gotoPage(this.curPage);
			}
		}
	};
	
	pager.prototype.toNextPage = function() {
		if (this.hasNextPage) {
			if (this.options && this.options.url) {
				if (this.curPage >= this.totalPage || this.curPage < 1) {
					this.curPage = 1;
				} else {
					this.curPage = this.curPage + 1;
				}
				this.gotoPage(this.curPage);
			}
		}
	};
	
	pager.prototype.gotoPage = function(pageNo) {
		if (pageNo) {
			this.checkAll = false;
			if (pageNo > this.totalPage || pageNo < 1) {
				pageNo = 1;
			}
			this.curPage = pageNo;
			if (this.options && this.options.url) {
				this.options.params.page = this.curPage;
				this.options.params.rows = this.pageSize;
				this.query({
					url:this.options.url,
					params:this.options.params
				});
			}
		}
	};
	
	pager.prototype.toFirstPage = function() {
		if (this.hasPerPage) {
			this.gotoPage(1);
		}
	};
	
	pager.prototype.toLastPage = function() {
		if (this.hasNextPage) {
			this.gotoPage(this.totalPage);
		}
	};
	
	pager.prototype.prevPageDisabled = function(){
		return this.hasPerPage ? "" : "disabled"; 
	};
	
	pager.prototype.nextPageDisabled = function(){
		return this.hasNextPage ? "" : "disabled"; 
	};
	
	pager.prototype.leftLabel = function(){
		// return $.i18n.prop('pager_lel_left_2',this.rowCount);
	};
	
	pager.prototype.rightLabel = function(){
		return "第"+this.curPage+"页/总"+this.totalPage+"页"; 
	};
	
	pager.prototype.selectAll = function(){
		if (!this.singleSelect) {
			if (this.items && this.items.length > 0) {
				var _this = this;
				angular.forEach(this.items, function(value) {
					value._checked_ = _this.checkAll;
				});
			}
		} else {
			this.checkAll = false;
		}
	};
	
	pager.prototype.select = function (idx,item) {
		if (this.singleSelect) {
			if (this.items && item) {
				angular.forEach(this.items, function(value) {
					value._checked_ = false;
				});
				item._checked_ = true;
			}
		}
	};
	
	pager.prototype.getSelectItems = function (){
		var selItems = [],i;
		if (this.items) {
			for (i = 0 ;i < this.items.length ; i++) {
				if (this.items[i]._checked_) {
					selItems.push(this.items[i]);
				}
			}
		}
		return selItems;
	};
	
	pager.prototype.getSelectIds = function (){
		var selItems = [],i;
		if (this.items) {
			for (i = 0 ;i < this.items.length ; i++) {
				if (this.items[i]._checked_) {
					selItems.push(this.items[i][this.idKey]);
				}
			}
		}
		return selItems;
	};
	
	pager.prototype.getItemByIdkey = function (idKeyVal){
		if (this.items) {
			var i;
			for (i = 0 ;i < this.items.length ; i++) {
				if (this.items[i][this.idKey] == idKeyVal) {
					return this.items[i];
				}
			}
		}
		return null;
	};
	
	var smartApp = {
		init: function init(_scope, opts) {
			return new pager(_scope, opts);
		}
	};
	
	return smartApp;
}]);


mainApp.config([ '$routeProvider', function($routeProvider) {
	$routeProvider.when('/welcome', {
		templateUrl : 'pages/welcome.html',
		controller : 'mainController'
	}).when('/taskTracker', {
		templateUrl : 'pages/taskTracker.jsp',
		controller : 'taskTrackerController'
	}).when('/task', {
		templateUrl : 'pages/task.jsp',
		controller : 'taskController'
	}).when('/taskRunDetail/:taskId', {
		templateUrl : 'pages/taskRunDetail.jsp',
		controller : 'taskRunDetailController'
	}).when('/taskEdit/:taskId/:isEdit', {
		templateUrl : 'pages/taskAdd.jsp',
		controller : 'taskEditController'
	}).when('/job', {
		templateUrl : 'pages/job.jsp',
		controller : 'jobController'
	}).when('/jobAdd', {
		templateUrl : 'pages/jobAdd.jsp',
		controller : 'jobAddController'
	}).when('/jobAdd/:jobId', {
		templateUrl : 'pages/jobAdd.jsp',
		controller : 'jobAddController'
	}).when('/alarm', {
		templateUrl : 'pages/alarm.jsp',
		controller : 'alarmController'
	}).when('/exce', {
		templateUrl : 'pages/taskItemException.jsp',
		controller : 'exceController'
	}).when('/user', {
        templateUrl : 'pages/user/users.jsp',
        controller : 'userController'
    }).otherwise({
		redirectTo : '/welcome'
	});
} ]);



mainApp.run(['$rootScope', '$window', '$location', '$log','$timeout', function ($rootScope, $window, $location, $log,$timeout) {  
	var pageSize = 10;
	if(window.localStorage){
		var config = window.localStorage.getItem('config'),
			defaultConfig = {'pageSize':pageSize};
		if (null == config || config =="") {
			window.localStorage.setItem('config',JSON.stringify(defaultConfig));
		} else {
			try {
				pageSize = parseInt(JSON.parse(config).pageSize);
			}catch(error) {
				window.localStorage.setItem('config',JSON.stringify(defaultConfig));
			}
		}
	}
	$rootScope.pageSize = pageSize;
	
	$rootScope.getCurrentTime=function(){
		return new Date().getTime();
	}
  
    function locationChangeStart(event) {}  
  
    function locationChangeSuccess(event) {}  
  
    function routeChangeStart(event) {}  
  
    function routeChangeSuccess(event) {
    	
    }  
}]);  

mainApp.controller('mainController', ['$rootScope','$scope','$window','$modal','$http',
	function ($rootScope,$scope,$window, $modal, $http) {
	$rootScope.selectItemKey = "";
	$rootScope.hasInital = false;
	$rootScope.menuItem = [];

	if (!$rootScope.hasInital) {

        $rootScope.hasInital = true;
        $http.post('job.do?cmd=user$getLoginUser', {}, postCfg).success(function(data) {
            $rootScope.menuItem = [];
            $rootScope.menuItem.push({
                key : "node",
                name : "节点信息",
                url : '/taskTracker'
            }, {
                key : "task",
                name : "任务",
                url : '/task'
            }, {
                key : "job",
                name : "作业",
                url : '/job'
            }, {
                key : "log",
                name : "告警信息",
                url : '/alarm'
            }, {
                key : "exce",
                name : "异常任务项",
                url : '/exce'
            });
            if (null != data && data.admin) {
                $rootScope.menuItem.push({
                    key : "user",
                    name : "用户管理",
                    url : '/user'
                });
            }
        });
	}

	$rootScope.menuClick = function(key) {
		$rootScope.selectItemKey = key;
	};
	
	$rootScope.logout=function(){
		if (confirm("确认退出登录吗？")) {
			$window.location.href="job.do?cmd=logout";
		}
	}

        $rootScope.updatePwd=function(){
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'pages/user/updatePwd4self.jsp',
                controller: 'updatePwd4selfController',
                resolve: {
                    params:function () { return {}; }
                }
            });

            modalInstance.result.then(function (refresh) {

            });
        }
	
	$rootScope.keyword="";

}]);

mainApp.controller('taskTrackerController', ['$rootScope','$scope','smartPager','$location','$http','$timeout', 
                                             function ($rootScope,$scope,smartPager,$location, $http, $timeout) {
	$rootScope.selectItemKey='node';
	
	// log
	$scope.queryParam = {taskTrackerUuid:null,startTime:null,entTime:null};
	
    var opts = {
    		singleSelect: false,
    		url: 'job.do?cmd=queryTaskTrackerLog',
    		pageSize:$rootScope.pageSize,
    		params:$scope.queryParam,
    		idKey:'_id',
    		beforeSend:function(){
    		},
    		success:function(data){
    		}
    };
    $scope.logpager = smartPager.init($scope, opts);
    $scope.logpager.load();
	
	
	// tasktracker
	$scope.taskTrackers = [];

	$scope.loadTaskTracker = function() {
		$http.post('job.do?cmd=queryAllTaskTracker', {}).success(
				function(data) {
					$scope.taskTrackers = data;

				});
	};
	$scope.loadTaskTracker();

	var intervalFun,
		intervalFunction = function() {
			intervalFun = $timeout(function myFunction() {
				$scope.loadTaskTracker();
				intervalFun = $timeout(intervalFunction, 1500);
			}, 1500);
		};

	intervalFunction();

	$scope.$on('$destroy', function(e) {
		$timeout.cancel(intervalFun);
	});
	
	$('#ttLogDetail').on('show.bs.modal', function (event) {
		var button = $(event.relatedTarget), // Button that triggered the modal
  	  		index = button.data('whatever'), // Extract info from data-* attributes
  	  		modal = $(this),
  	  		item = $scope.logpager.items[index],
  	  		date = new Date(item.logTime);
		modal.find('.modal-body input').val("jobID：" + item.jobId + "        taskId : " + item.taskId + "        logTime : " + date.pattern("yyyy-MM-dd hh:mm:ss") + "    logType : " + item.logType);
		modal.find('.modal-body textarea').val(item.content);
  });
	
	// jobtracker list

	$scope.jobTrackerNodes = [];

	$scope.queryJobTrackerNodes = function() {
		$http.post('job.do?cmd=queryJobtrackerNodes', {}).success(
				function(data) {
					$scope.jobTrackerNodes = data;
				});
	};
	$scope.queryJobTrackerNodes();


	// blackList start


	 $scope.blackList = [];

	 $scope.queryblackList = function() {
		 $http.post('job.do?cmd=queryBlackList', {}).success(
			 function(data) {
                 if (data) {
					 $scope.blackList = data.split(",");
				 } else {
                     $scope.blackList=[];
				 }

			 });
	 };
	 $scope.queryblackList();

	// blacklist end
	
	$scope.clearCache=function(event,uuid) {
		try {
			$(event.target).button("loading...");
			$http.post('job.do?cmd=clearCache', {uuid:uuid},postCfg).success(
					function(data) {
						if (data.success) {
							alert('操作成功');
						} else {
							alert('操作失败');
						}
					});
		}
		finally {
			$(event.target).button("reset");
		}
	}

}]);

mainApp.controller('taskController', ['$rootScope','$scope','$http','smartPager','$timeout','$modal',
                                      function ($rootScope,$scope, $http,smartPager,$timeout,$modal) {
	$rootScope.selectItemKey='task';
	$scope.taskQuery = {queryJobId:null,taskName:null, taskGroup:null};
	$scope.tasks = [];
	
	$scope.query=function(){
		$http.post('job.do?cmd=queryTaskList&t='+new Date().getTime(), {taskQuery:JSON.stringify($scope.taskQuery)},postCfg).success(function(data) {
			$scope.tasks = data;

		});
	}
	$scope.query();
	
	// log
	$scope.queryParam = {taskId:null,startTime:"",endTime:""};
    var opts = {
    		singleSelect: false,
    		url: 'job.do?cmd=queryTaskLog',
    		pageSize:$rootScope.pageSize,
    		params:{logQuery:function(){
    			var newObject = $.extend(true, {}, $scope.queryParam);
    			newObject.startTime = Date.parse(newObject.startTime);
    			newObject.endTime = Date.parse(newObject.endTime);
    			return JSON.stringify(newObject);
    		}},
    		idKey:'_id',
    		beforeSend:function(){
    		},
    		success:function(data){
    		}
    };
    $scope.logpager = smartPager.init($scope, opts);
    $scope.logpager.load();
	
	// task run record
	$scope.queryRunRecordParam = {taskTrackerUuid:null,startTime:null,entTime:null};
	
    var opts = {
    		singleSelect: false,
    		url: 'job.do?cmd=queryTaskRunRecord',
    		pageSize:$rootScope.pageSize,
    		params:$scope.queryRunRecordParam,
    		idKey:'_id',
    		beforeSend:function(){
    		},
    		success:function(data){
    		}
    };
    $scope.runRecordPager = smartPager.init($scope, opts);
    $scope.runRecordPager.load();
	
	$('#tLogDetail').on('show.bs.modal', function (event) {
	  	  var button = $(event.relatedTarget), // Button that triggered the
												// modal
	  	  index = button.data('whatever'), // Extract info from data-*
												// attributes
	  	  modal = $(this),
	  	  item = $scope.logpager.items[index],
	  	  date = new Date(item.logTime);
	  	  modal.find('.modal-body input').val("jobID：" + item.jobId + "        taskId : " + item.taskId + "        logTime : " + date.pattern("yyyy-MM-dd hh:mm:ss") + "    logType : " + item.logType);
	  	  modal.find('.modal-body textarea').val(item.content);
	});
	
	$scope.openEditDialog = function (taskId, isEdit) {
		
	    var modalInstance = $modal.open({
	      animation: true,
	      templateUrl: 'pages/taskAddDialog.jsp',
	      controller: 'taskEdit4DialogController',
	      resolve: {
	    	  params:function () { return {taskId:taskId,isEdit:isEdit}; }
	      }
	    });
	    
	    modalInstance.result.then(function (refresh) {
	        if (refresh) $scope.query();
	    });
	 };

}]);



mainApp.controller('taskEdit4DialogController', ['$rootScope','$scope','$http','$timeout','$routeParams','$location', '$modalInstance', 'params',
                                          function ($rootScope,$scope, $http, $timeout, $routeParams, $location, $modalInstance, params) {
	$rootScope.selectItemKey='task';
	$scope.task = {};
	$scope.isEdit = params.isEdit;
	var taskId = params.taskId;
	$http.post('job.do?cmd=queryTaskById', {
		taskId : taskId
	}, postCfg).success(function(data) {
		$scope.task = data;
	});

	$scope.saveTask = function() {
		var reg = new RegExp("^([1-9][0-9]*)$");
		
		if ($scope.task.interfaceType == 'SCHEDULE_TASK_MUTIL') {
			if (!reg.test($scope.task.threadsOfRegion)) {
				alert('taskTracker开启线程数必须大于等于1');
				return;
			}
			if (!reg.test($scope.task.eachFetchDataNum)) {
				alert('每次抓取数据的数量必须大于等于1');
				return;
			}
		}
		
		if (confirm("确认保存？")) {
			$http.post('job.do?cmd=saveTask', {
				task : JSON.stringify($scope.task)
			}, postCfg).success(function(data) {
				if (data.success == 'true' || data.success == true) {
					alert('保存成功');
				} else {
					alert("保存失败：" + data.message);
				}
				$modalInstance.close(true);
			});
		}
	};

	$scope.returnPage = function() {
		$modalInstance.dismiss('cancel');
	};
	
}]);

mainApp.controller('taskRunDetailController', ['$rootScope','$scope','$http','$timeout','$routeParams',function ($rootScope,$scope,
		$http, $timeout, $routeParams) {
	$rootScope.selectItemKey='task';

	$scope.data = {};
	var taskId = $routeParams.taskId;

	$scope.loadTask = function() {
		$http.post('job.do?cmd=queryTaskRunDetail&taskId=' + taskId, {})
				.success(function(data) {
					// alert(JSON.stringify(data));
					$scope.data = data;
				});
	};
	$scope.loadTask();

	$scope.stopTask = function(taskId) {
		if (confirm("确认发送暂停任务调度命令?")) {
			$http.post('job.do', {
				cmd : 'stopTask',
				taskId : taskId
			}, postCfg).success(function(data) {
				if (data.success == true || data.success == 'true') {
					alert("已发送暂停命令, 请等待所有任务项停止运行。");
				} else {
					alert("发送暂停命令异常:" + data.message);
				}
				$scope.loadTask();
			});
		}
	};

	$scope.startTask = function(taskId) {
		if (confirm("确认启动任务调度?")) {
			$http.post('job.do', {
				cmd : 'startTask',
				taskId : taskId
			}, postCfg).success(function(data) {
				if (data.success == true || data.success == 'true') {
					alert("启动成功");
				} else {
					alert("操作失败:" + data.message);
				}
				$scope.loadTask();
			});
		}
	};

	$scope.delTask = function(taskId) {
		$http.post('job.do?cmd=delTask&taskId=' + taskId, {}).success(
				function(data) {
					// alert(JSON.stringify(data));
					$scope.data = data;
				});
	};

	var intervalFun,
		intervalFunction = function() {
		intervalFun = $timeout(function myFunction() {
			$scope.loadTask();
			intervalFun = $timeout(intervalFunction, 1500);
		}, 1500);
	};

	intervalFunction();

	$scope.$on('$destroy', function(e) {
		$timeout.cancel(intervalFun);
	});
}]);

mainApp.controller('taskEditController', ['$rootScope','$scope','$http','$timeout','$routeParams','$location',
                                          function ($rootScope,$scope, $http, $timeout, $routeParams, $location) {
	$rootScope.selectItemKey='task';
	$scope.task = {};
	var taskId = $routeParams.taskId;
	$scope.isEdit = $routeParams.isEdit;
	$http.post('job.do?cmd=queryTaskById', {
		taskId : taskId
	}, postCfg).success(function(data) {
		$scope.task = data;
	});

	$scope.saveTask = function() {
		var reg = new RegExp("^([1-9][0-9]*)$");
		
		if ($scope.task.interfaceType == 'SCHEDULE_TASK_MUTIL') {
			if (!reg.test($scope.task.threadsOfRegion)) {
				alert('taskTracker开启线程数必须大于等于1');
				return;
			}
			if (!reg.test($scope.task.eachFetchDataNum)) {
				alert('每次抓取数据的数量必须大于等于1');
				return;
			}
		}
		
		if (confirm("确认保存？")) {
			$http.post('job.do?cmd=saveTask', {
				task : JSON.stringify($scope.task)
			}, postCfg).success(function(data) {
				if (data.success == 'true' || data.success == true) {
					alert('保存成功');
					$location.path("/task");
				} else {
					alert("保存失败：" + data.message);
				}
			});
		}
	};

	$scope.returnPage = function() {
		$location.path("/task");
	};
}]);

mainApp.controller('jobController', ['$rootScope','$scope','$http','smartPager','$timeout','$routeParams','$location','$modal',
                                     function ($rootScope,$scope, $http,smartPager,	$timeout, $routeParams, $location, $modal) {
	$rootScope.selectItemKey='job';
	// log
	$scope.queryParam = {jobId:null,jobName:null,startTime:"",entTime:""};
	
    var opts = {
    		singleSelect: false,
    		url: 'job.do?cmd=queryJobLog',
    		pageSize:$rootScope.pageSize,
    		params:{logQuery:function(){
				var newObject = $.extend(true, {}, $scope.queryParam);
				newObject.startTime = Date.parse(newObject.startTime);
				newObject.endTime = Date.parse(newObject.endTime);
				return JSON.stringify(newObject);
			}},
    		idKey:'_id',
    		beforeSend:function(){
    		},
    		success:function(data){
    		}
    };
    $scope.logpager = smartPager.init($scope, opts);
    $scope.logpager.load();
    
    $scope.logQuery=function(){
    	$scope.logpager.load($scope.queryParam);
    };
	
	
	// job
	$scope.jobQueryParam = {jobId:null,jobName:null,jobStatus:""};
	$scope.tasks = [];
	$scope.queryJobs=function(){
		$http.post('job.do?cmd=queryAllJobs',{jobQuery:JSON.stringify($scope.jobQueryParam)},postCfg).success(function(data){
				$scope.jobs = data;
			
		});
	};
	$scope.queryJobs();
	
	$scope.delJob=function(jobId){
		if (confirm('确认删除吗？')) {
			$http.post('job.do?cmd=delJob',{jobId:JSON.stringify(jobId)},postCfg).success(function(data){
				if (data.success == true || data.success == 'true') {
					$scope.queryJobs();
					alert('删除成功');
				} else {
					alert('删除失败' + data.message);
				}
			});
		}
	};
	
	$scope.startJob=function(jobId){
		if (confirm('确认启动作业吗？')) {
			$http.post('job.do?cmd=startJob',{jobId:JSON.stringify(jobId)},postCfg).success(function(data){
				if (data.success == true || data.success == 'true') {
					alert('启动成功');
				} else {
					alert('启动失败' + data.message);
				}
				$scope.queryJobs();
			});
		}
	};
	
	$scope.stopJob=function(jobId){
		if (confirm('确认停止作业吗？')) {
			$http.post('job.do?cmd=stopJob',{jobId:JSON.stringify(jobId)},postCfg).success(function(data){
				if (data.success == true || data.success == 'true') {
					alert('停止作业成功');
				} else {
					alert('停止作业失败' + data.message);
				}
				$scope.queryJobs();
			});
		}
	};
	

	$('#jobLogDetail').on('show.bs.modal', function (event) {
  	  var button = $(event.relatedTarget), // Button that triggered the modal
  	  index = button.data('whatever'), // Extract info from data-*
											// attributes
  	  modal = $(this),
  	  item = $scope.logpager.items[index],
  	  date = new Date(item.logTime);
  	  modal.find('.modal-body input').val("jobID：" + item.jobId + "    taskId : " + item.taskId + "     logTime : " + date.pattern("yyyy-MM-dd hh:mm:ss") + "    logType : " + item.logType);
  	  modal.find('.modal-body textarea').val(item.content);
  });
	
	
	$scope.openEditDialog = function (jobId, isEdit) {
		
	    var modalInstance = $modal.open({
	      animation: true,
	      templateUrl: 'pages/jobAddDialog.jsp',
	      controller: 'jobAdd4DialogController',
	      resolve: {
	    	  params:function () { return {jobId:jobId,isEdit:isEdit}; }
	      }
	    });
	    modalInstance.result.then(function (refresh) {
	    	if (refresh) $scope.queryJobs();
	    });
	};
}]);

mainApp.controller('jobAdd4DialogController', ['$rootScope','$scope','$http','$timeout', '$modalInstance', 'params',
                                        function ($rootScope,$scope, $http,	$timeout, $modalInstance, params) {
	$scope.job = {};
	$scope.tasks=[];
	$scope.taskIds=[];
	$scope.unRatedTasks=[];
	var jobId = params.jobId;
	$scope.isEdit=params.isEdit;
	if (jobId && jobId!='null') {
		$http.post('job.do?cmd=queryJobById',{jobId:jobId},postCfg).success(function(data){
			$scope.job = data;
			
			$http.post('job.do?cmd=queryAllretadTasks',{jobId:JSON.stringify(data.jobId)},postCfg).success(function(data){
				$scope.tasks = data;
				if (data && data.length && data.length>0) {
					for (var i = 0 ;i < data.length ;i++) {
						$scope.taskIds.push(data[i].taskId.taskId);
					}
				}
			});
		});
	} else {
		$scope.job = {jobName:'',runStartTime:'',runEndTime:'',remark:''};
	}
	
	$http.post('job.do?cmd=queryAllUnretadTasks',{},postCfg).success(function(data){
		$scope.unRatedTasks = data;
	});
	
    
	$scope.saveJob=function(){
		if (!$scope.job.jobName || $scope.job.jobName == '') {
			alert('请输入作业名称');
			return;
		}
		if ($scope.job.jobName.length > 64) {
			alert('作业名称的长度必须小于等于64个字符');
			return;
		}
		if (!$scope.job.runStartTime || $scope.job.runStartTime == '') {
			alert('请输入作业开始运行时间');
			return;
		}
		
		if ($scope.taskIds.length == 0) {
			alert('请选择任务');
			return ;
		}
		if (!$scope.job.remark && $scope.job.remark.length > 128) {
			alert('备注的长度必须小于等于128个字符');
			return;
		}
		
		if (confirm("确认保存？")) {
			var param ={job:JSON.stringify($scope.job),taskIds:$scope.taskIds.join(",")};
			$http.post('job.do?cmd=saveJob',param,postCfg).success(function(data){
				if (data.success){
					alert('保存成功');
				} else {
					alert('保存失败,' + data.message);
				}
				$modalInstance.close(true);
			});		
		}
	};
	
	$scope.selectTask=function(task,index){
		/*
		 * if ($scope.taskIds.length == 1) { alert('一个作业只能添加一个任务'); return; }
		 */
		$scope.unRatedTasks.splice(index,1);
		$scope.tasks.push(task);
		$scope.taskIds.push(task.taskId.taskId);
	};
	
	$scope.removeTask=function(task,index){
		$scope.tasks.splice(index,1);
		$scope.taskIds.splice(index,1);
		$scope.unRatedTasks.push(task);
	};
	
	$scope.returnPage=function(){
		$modalInstance.dismiss('cancel');
	};
}]);

mainApp.controller('jobAddController', ['$rootScope','$scope','$http','$timeout','$routeParams','$location',
                                        function ($rootScope,$scope, $http,	$timeout, $routeParams, $location) {
	$rootScope.selectItemKey='job';
	$scope.job = {};
	$scope.tasks=[];
	$scope.taskIds=[];
	$scope.unRatedTasks=[];
	var jobId = $routeParams.jobId;
	if (jobId && jobId!='null') {
		$http.post('job.do?cmd=queryJobById',{jobId:jobId},postCfg).success(function(data){
			$scope.job = data;
			
			$http.post('job.do?cmd=queryAllretadTasks',{jobId:JSON.stringify(data.jobId)},postCfg).success(function(data){
				$scope.tasks = data;
				if (data && data.length && data.length>0) {
					for (var i = 0 ;i < data.length ;i++) {
						$scope.taskIds.push(data[i].taskId.taskId);
					}
				}
			});
		});
	} else {
		$scope.job = {jobName:'',runStartTime:'',runEndTime:'',remark:''};
	}
	
	$http.post('job.do?cmd=queryAllUnretadTasks',{},postCfg).success(function(data){
		$scope.unRatedTasks = data;
	});
	
    
	$scope.saveJob=function(){
		if (!$scope.job.jobName || $scope.job.jobName == '') {
			alert('请输入作业名称');
			return;
		}
		if (!$scope.job.runStartTime || $scope.job.runStartTime == '') {
			alert('请输入作业开始运行时间');
			return;
		}
		
		if ($scope.taskIds.length == 0) {
			alert('请选择任务');
			return ;
		}
		
		if (confirm("确认保存？")) {
			var param ={job:JSON.stringify($scope.job),taskIds:$scope.taskIds.join(",")};
			$http.post('job.do?cmd=saveJob',param,postCfg).success(function(data){
				if (data.success){
					alert('保存成功');
					$location.path("/job");
				} else {
					alert('保存失败,' + data.message);
				}
			});		
		}
	};
	
	$scope.selectTask=function(task,index){
		/*
		 * if ($scope.taskIds.length == 1) { alert('一个作业只能添加一个任务'); return; }
		 */
		$scope.unRatedTasks.splice(index,1);
		$scope.tasks.push(task);
		$scope.taskIds.push(task.taskId.taskId);
	};
	
	$scope.removeTask=function(task,index){
		$scope.tasks.splice(index,1);
		$scope.taskIds.splice(index,1);
		$scope.unRatedTasks.push(task);
	};
	
	$scope.returnPage=function(){
		$location.path("/job");
	};

}]);



mainApp.controller('alarmController', ['$rootScope','$scope','$http','smartPager','$timeout','$routeParams','$location',
                                       function ($rootScope,$scope, $http,smartPager,$timeout, $routeParams, $location) {
	$rootScope.selectItemKey='log';
		
	// taskTracker disconnect log
	$scope.ttQueryParam = {ip:null,startTime:null,entTime:null};
	
    var opts = {
    		singleSelect: false,
    		url: 'job.do?cmd=queryTaskTrackerDisconnectLog',
    		pageSize:$rootScope.pageSize,
    		params:$scope.ttQueryParam,
    		idKey:'_id',
    		beforeSend:function(){
    		},
    		success:function(data){
    		}
    };
    $scope.ttpager = smartPager.init($scope, opts);
    $scope.ttpager.load();
    
    $scope.ttlogQuery=function(){
    	$scope.ttpager.load($scope.ttQueryParam);
    };
    
    
	// task exe failure log
	$scope.tfQueryParam = {ip:null,startTime:null,entTime:null};
	
    var opts2 = {
    		singleSelect: false,
    		url: 'job.do?cmd=queryTaskExeFailureLog',
    		pageSize:$rootScope.pageSize,
    		params:$scope.tfQueryParam,
    		idKey:'_id',
    		beforeSend:function(){
    		},
    		success:function(data){
    		}
    };
    $scope.tfpager = smartPager.init($scope, opts2);
    $scope.tfpager.load();
    
    $scope.tflogQuery=function(){
    	$scope.tfpager.load($scope.tfQueryParam);
    };
    
    $('#alarmDetail').on('show.bs.modal', function (event) {
    	  var button = $(event.relatedTarget), // Button that triggered the
												// modal
    	  index = button.data('whatever'), // Extract info from data-*
												// attributes
    	  modal = $(this),
    	  item = $scope.tfpager.items[index],
    	  date = new Date(item.logTime);
    	  modal.find('.modal-body input').val("jobID：" + item.jobId + "        taskId : " + item.taskId + "        logTime : " + date.pattern("yyyy-MM-dd hh:mm:ss"));
    	  modal.find('.modal-body textarea').val(item.content);
    });

}]);



mainApp.controller('exceController', ['$rootScope','$scope','$http','smartPager','$timeout','$routeParams','$location',
                                       function ($rootScope,$scope, $http,smartPager,$timeout, $routeParams, $location) {
	$rootScope.selectItemKey='exce';
    
	$scope.taskItemQuery = {taskTrackerIp:null,queryJobId:null, queryTaskId:null};
		
	$scope.taskItems = [];
    $scope.query=function(){
    	$http.post('job.do?cmd=queryStatusExceptionTaskItem', {taskItemQuery:JSON.stringify($scope.taskItemQuery)},postCfg).success(function(data) {
    		$scope.taskItems = data;
			if ($scope.ckAllSelected) {
				$scope.ckAllSelected = false;
			}
    	});
    };
    $scope.query();
    
    $scope.recovery=function(taskItemId){
    	if (confirm("确认恢复任务项运行吗？")) { 
    		$http.post('job.do?cmd=recoveryTaskItem',{id:taskItemId},postCfg).success(function(data){
				if (data.success == true || data.success == 'true') {
					alert('操作成功');
				} else {
					alert('操作失败' + data.message);
				}
				$scope.query();
			});
    	}
    }
    
    $scope.recoverySelected=function() {
    	if ($scope.taskItems && $scope.taskItems.length > 0) {
    		var selectedIds = [];
    		for (var i = 0 ; i < $scope.taskItems.length ; i ++) {
				if ($scope.taskItems[i].selected) {
					selectedIds.push($scope.taskItems[i].taskItemId);
				}
			}
    		if (selectedIds.length > 0) { 
    			if (confirm("确认恢复所选任务项运行吗？")) {
    				$http.post('job.do?cmd=recoveryTaskItem',{id:selectedIds.join(',')},postCfg).success(function(data){
    					if (data.success == true || data.success == 'true') {
    						alert('操作成功');
    					} else {
    						alert('操作失败' + data.message);
    					}
    					if ($scope.ckAllSelected) {
    						$scope.ckAllSelected = false;
    					}
    					$scope.query();
    				});
    			}
    		} else {
    			alert('请选择需要恢复的任务项!');
    		}
    	} else {
    		alert('请选择需要恢复的任务项!');
    	}
    }
    
    $scope.selected=function(index){
    	$scope.taskItems[index].selected = !$scope.taskItems[index].selected;
    }
    
    $scope.ckAllSelected = false;
    $scope.selectedAll=function() {
    	var selected = $scope.ckAllSelected;
    	if ($scope.taskItems && $scope.taskItems.length > 0) {
    		for (var i = 0 ; i < $scope.taskItems.length ; i ++) {
    			$scope.taskItems[i].selected = selected;
			}
    	}
    }
    
    // 任务项状态查询
    $scope.taskItemStatus = [{value:"INACTIVIE", selected:false},
                               {value:"PUSH", selected:false},
                               {value:"ACTIVIE", selected:false},
                               {value:"COMPLETE", selected:false},
                               {value:"STOP", selected:false}];
    
	$scope.taskItem4StatusQuery = {taskTrackerIp:null,queryJobId:null, queryTaskId:null,taskItemStatusList:null};
	
	$scope.taskItems4Status = [];
	$scope.longTime = null;
    $scope.query4Status=function(){
    	var selectedStatus = [];
    	for (var i = 0 ; i < $scope.taskItemStatus.length ; i++) {
    		if ($scope.taskItemStatus[i].selected) selectedStatus.push($scope.taskItemStatus[i].value);
    	}
    	if (selectedStatus.length > 0){
    		$scope.taskItem4StatusQuery.taskItemStatusList= selectedStatus;
    	} else {
    		$scope.taskItem4StatusQuery.taskItemStatusList = null;
    	}
    	
    	$http.post('job.do?cmd=queryTaskItems4status', {taskItemQuery:JSON.stringify($scope.taskItem4StatusQuery),longTime:$scope.longTime},postCfg).success(function(data) {
    		$scope.taskItems4Status = data;
    	});
    };

}]);


